using UnityEngine;

/// <summary>
/// 玩家控制器：处理玩家的输入、动画和碰撞
/// </summary>
public class PlayerController : MonoBehaviour
{
    [Header("基础设置")]
    [Tooltip("跳跃力度")]
    [SerializeField] private float jumpForce = 10f;
    [Tooltip("重力系数")]
    [SerializeField] private float gravityModifier = 1.5f;

    [Header("粒子效果")]
    [Tooltip("灰尘粒子效果")]
    [SerializeField] private ParticleSystem dustParticle;
    [Tooltip("爆炸粒子效果")]
    [SerializeField] private ParticleSystem explosionParticle;

    [Header("音频设置")]
    [Tooltip("跳跃音效")]
    [SerializeField] private AudioClip jumpSound;
    [Tooltip("碰撞音效")]
    [SerializeField] private AudioClip crashSound;

    // 私有成员变量
    private Rigidbody playerRb;
    private Animator playerAnim;
    private AudioSource playerAudio;
    private bool isOnGround = true;
    private bool gameOver = false;

    // 动画参数名称
    private static readonly string JUMP_TRIG = "Jump_trig";
    private static readonly string DEATH_B = "Death_b";
    private static readonly string DEATH_TYPE_INT = "DeathType_int";

    void Start()
    {
        // 获取组件引用
        playerRb = GetComponent<Rigidbody>();
        playerAnim = GetComponent<Animator>();
        playerAudio = GetComponent<AudioSource>();

        // 设置物理重力
        Physics.gravity *= gravityModifier;
    }

    void Update()
    {
        // 游戏结束时不处理输入
        if (gameOver) return;

        // 检测跳跃输入
        if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
        {
            Jump();
        }
    }

    /// <summary>
    /// 处理跳跃逻辑
    /// </summary>
    private void Jump()
    {
        // 施加向上的力
        playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        
        // 更新状态
        isOnGround = false;
        
        // 播放动画
        playerAnim.SetTrigger(JUMP_TRIG);
        
        // 停止灰尘特效
        dustParticle.Stop();
        
        // 播放音效
        playerAudio.PlayOneShot(jumpSound, 1.0f);
    }

    /// <summary>
    /// 处理碰撞开始事件
    /// </summary>
    private void OnCollisionEnter(Collision collision)
    {
        // 检查碰撞对象的标签
        if (collision.gameObject.CompareTag("Ground"))
        {
            // 着地处理
            isOnGround = true;
            // 播放灰尘特效
            if (!gameOver)
            {
                dustParticle.Play();
            }
        }
        else if (collision.gameObject.CompareTag("Obstacle"))
        {
            Die();
        }
    }

    /// <summary>
    /// 处理死亡逻辑
    /// </summary>
    private void Die()
    {
        // 更新状态
        gameOver = true;
        
        // 播放死亡动画
        playerAnim.SetBool(DEATH_B, true);
        playerAnim.SetInteger(DEATH_TYPE_INT, 1);
        
        // 播放特效
        explosionParticle.Play();
        dustParticle.Stop();
        
        // 播放音效
        playerAudio.PlayOneShot(crashSound, 1.0f);
    }

    /// <summary>
    /// 获取游戏状态
    /// </summary>
    public bool IsGameOver()
    {
        return gameOver;
    }
} 